#include <iostream>
#include <sys/types.h>        
#include <sys/socket.h>
#include <unistd.h>
#include <string>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

class Udp_Server
{
public:

    Udp_Server(int port, string ip)
        :_socket(-1)
        ,_port(port)
        ,_ip(ip)
    {}


    bool UdpServer_init()
    {
        //1. 创建套接字socket;
        _socket = socket(AF_INET, SOCK_DGRAM, 0);
        if(_socket < 0)
        {
            perror("socket fail!");
            return false;
        }
        cout << "socket success! " << _socket << endl;
        //return true;

        //绑定bind;
        struct sockaddr_in local;
        memset(&local, '\0', sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());

        if(bind(_socket, (sockaddr*)&local, sizeof(sockaddr)) < 0)
        {
            cerr << "bind error! " << endl;
            return false;
        }
        cout << "bind success! " << endl;
        return true;
    }

    void Start()
    {
    #define SIZE 128
        char buff[SIZE];
        for(;;)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t ret = recvfrom(_socket, buff, sizeof(buff)-1, 0, (sockaddr*)&peer, &len);
            if(ret > 0)
            {
                buff[ret] = '\0';
                int port = ntohs(peer.sin_port);
                string ip = inet_ntoa(peer.sin_addr);
                cout << "port: " << port << "  ip: " << ip << ": " << buff << endl;
            }
            else
            {
                cout << "recvfrom error!" << endl;
            }

            //回声器;将收到消息传递回去;
            string mess_ret = "server return-> ";
            mess_ret += buff;
            sendto(_socket, &mess_ret, mess_ret.size(), 0, (sockaddr*)&peer, len);
        }
    }


    ~Udp_Server()
    {
        if(_socket >= 0)
        {
            close(_socket);
        }
    }

private:
    int _socket;
    int _port;
    string _ip;
};

// int main()
// {
//     // Udp_Server* sur = new Udp_Server();
//     // sur->UdpServer_init();

//     Udp_Server* sur = new Udp_Server(8080, "127.0.0.1");
//     sur->UdpServer_init();
//     return 0;
// }

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        cerr << "Usage: " << argv[0] << "port" << endl;
        return 1;
    }

    string ip = "127.0.0.1";//回环地址;
    int port = atoi(argv[1]);
    Udp_Server* sur = new Udp_Server(port, ip);
    sur->UdpServer_init();
    sur->Start();
    return 0;
}